import axios, { AxiosError, type Method } from 'axios'
import {useUserStore} from '@/stores/index'
import { showFailToast } from 'vant'
import router from '@/router'
export const baseURL='https://consult-api.itheima.net'
const instance = axios.create({
  //  1. 基础地址，超时时间
  baseURL,
  timeout: 10000
})
//请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 2.获取token
     const store = useUserStore()
     //判断是否有token
     if(store.user?.token && store.user){
      //请求头
      config.headers.Authorization =`Bearer ${store.user.token}`
     }
    return config
  },
  (err) => Promise.reject(err)
)
//响应拦截器
instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if(res.data.code!==10000){
      //轻提示
      showFailToast(res.data?.message||'业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err:AxiosError) => {
    // TODO 5. 处理401错误
    if(err.response?.status === 401){
      //清空token
      const store = useUserStore()
      store.delStore()
      //跳转登录页面
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default instance

//封装函数
type ResDataType<T> ={
  code:number
  message:string
  data:T
}
export function request<T>(
  url:string,
  method:Method = 'GET',
  submitData?:object
){
   return instance.request<any,ResDataType<T>>({
    url,
    method,
    [method.toUpperCase()==='GET'?'params':'data']:submitData
   })
}